import { apiUrl } from '@/common/const';
import AuthModal, { AuthResult } from '@/pages/pc/components/AuthModal';
import OrderPayModal, { PayCode, PaySuccess } from '@/pages/pc/components/OrderPayModal';
import { allGet } from '@/services/pc';
import request from '@/utils/request';
import { message } from 'antd';
import { useRef } from 'react';
import { history, useModel } from 'umi';

// 测试id
// const sid = '96';
// 获取套餐订单详情
const getPackagesDetail = async (item) => {
  const response = await allGet({
    params: { mod: 'salesmix', do: 'add', version: 'pc1.0', sid: item.sid, mentor: item.mentor },
  });
  return response;
};

// 获取单个课程订单详情
const getCourseDetail = async (item) => {
  const response = await allGet({
    params: {
      mod: 'course',
      do: 'add',
      version: 'pc1.0',
      classid: item.classid,
      mentor: item.mentor,
    },
  });
  return response;
};

// 获取DLC课程章节详情
const getCourseDLCDetail = async (item) => {
  const response = await allGet({
    params: { mod: 'lesson', do: 'pay', version: 'pc1.0', lid: item.lid },
  });
  return response;
};

// 获取套餐支付二维码
const payPackagesStatusDetail = ({ balance, payType, fqiNum, sid, mentor }) =>
  allGet({
    params: {
      mod: 'salesmix',
      do: 'add',
      balance,
      paysubmit: 1,
      version: 'pc1.0',
      paytype: payType,
      fqipay_num: fqiNum,
      sid,
      mentor,
    },
  });
// 获取课程支付二维码
const payCourseStatusDetail = ({ balance, payType, fqiNum, classid, laxCode, sid, mentor }) => {
  const params = {
    mod: 'course',
    do: 'add',
    balance,
    paysubmit: 1,
    version: 'pc1.0',
    paytype: payType,
    fqipay_num: fqiNum,
    classid,
    sid,
    mentor,
  } as any;
  if (laxCode) {
    params.invitecode = laxCode;
  }
  return allGet({
    params,
  });
};

// 获取课程DLC支付二维码
const payCourseDLCStatusDetail = ({ balance, payType, lid }) => {
  const params = {
    mod: 'lesson',
    do: 'pay',
    balance,
    paysubmit: 1,
    version: 'pc1.0',
    paytype: payType,
    lid,
  } as any;
  return allGet({
    params,
  });
};

const useBuy = ({ onSuccess: propsOnSuccess = () => false as any } = {}) => {
  // '':正常
  // verify: 显示实名认证
  // contract: 显示签署合同
  const gotoRef = useRef('');
  const { getOrder } = useModel('order');
  const classDetailRef = useRef({});
  // 认证
  const handleAuth = () => {
    AuthModal.show({
      onSuccess: async (values, type) => {
        AuthResult.show({
          buttonText: '签署合同',
          onClick: () => {
            history.push('/learning?index=3');
          },
        });
      },
    });
  };
  // 支付成功弹窗
  const handlePaySuccess = async (type, payResultData) => {
    /**
     *  支付成功后去刷新全局上的订单数据
     *  用来更新顶部导航上的未支付订单提示
     *  如果是在订单页面，会刷新列表
     */
    getOrder();
    // 成功回调函数
    propsOnSuccess();

    // 显示弹窗
    PaySuccess.show({
      data: [],
      type,
      classDetail: classDetailRef.current,
      payResultData,
      // 去课程
      onGoCourse: () => {
        history.push(`/learning?classid=${classDetailRef.current?.classid}`);
      },
      // 开具发票
      onGoInvoice: () => {
        history.push('/learning?index=4');
      },
      // 点击实名认证
      onAuth: handleAuth,
      // 点击签署合同
      onSign: () => {
        window.location.href = '/learning?index=3';
        // history.push('/learning?index=3');
      },
      onClose: () => {
        window.location.reload();
      },
    });
  };

  // 支付成功后显示按钮状态判断
  const handleShowResult = (data, { isDlc = false } = {}) => {
    if (isDlc) {
      return message.success('支付成功');
    }
    // 1 正常 2 显示实名认证 3 显示签署合同
    let type = 1;

    if (gotoRef.current === 'contract') {
      type = 3;
    }
    if (gotoRef.current === 'verify') {
      type = 2;
    }
    PayCodeRef.current?.close?.();
    handlePaySuccess(type, data);

    return true;
  };

  // 定时器
  const timer = useRef<any>(null);

  // 支付查询状态
  const checkPayStatus = async ({
    paramsString,
    balance,
    payType,
    fqiNum,
    manual = false,
    isDlc = false,
  }) => {
    // 检查支付成没的接口
    const checkResponse = await request.get(`${apiUrl}?${paramsString}`);

    // 如果是手动点击已经完成支付按钮
    if (manual) {
      clearInterval(timer.current);
      PayCodeRef.current?.close?.();
      if (checkResponse?.data?.status !== 1) {
        return message.error('支付失败');
      }
      handleShowResult(checkResponse?.data, { isDlc });
      return;
    }

    // 支付成功
    if (checkResponse?.data?.status == 1) {
      clearInterval(timer.current);
      handleShowResult(checkResponse?.data, { isDlc });
    }
  };

  // 二维码弹窗ref
  const PayCodeRef = useRef<any>({});

  // 点击支付
  const handlePay = async ({
    payMoney,
    payType,
    fqiNum = 0,
    useBalance,
    balance,
    sid = 0,
    classid = 0,
    lid = 0,
    laxCode,
    secskill,
    isDlc = false,
    mentor = '',
  }: any) => {
    // const response = {
    //   success: true, data: {
    //     check: 'https://www.cgjoy.com/app.php?mod=pay&do=check&version=pc1.0&orderid=20220726142307MvGYJI8CxxxzgCcz2j',
    //     qr: '',
    //   }
    // }

    // const response = {"success":true,"code":0,"data":{"status":1,"msg":"\u4ed8\u6b3e\u6210\u529f\uff0c\u6211\u4eec\u5bf9\u5b66\u5458\u8981\u6c42\u8eab\u4efd\u8ba4\u8bc1\uff0c\u5c06\u4e2d\u8f6c\u5230\u8eab\u4efd\u8ba4\u8bc1\u9875\u9762\u3002","goto":"verify"}}
    let response = {} as any;
    if (sid) {
      response = await payPackagesStatusDetail({ balance, payType, fqiNum, sid, mentor });
    }
    if (classid) {
      response = await payCourseStatusDetail({
        balance,
        payType,
        fqiNum,
        classid,
        laxCode,
        sid: secskill?.sid || undefined,
        mentor,
      });
    }
    if (lid) {
      response = await payCourseDLCStatusDetail({ balance, payType, lid });
    }

    if (!response.success) {
      return;
    }
    // 记录需要实名认证还是签署合同状态
    gotoRef.current = response?.data?.goto;

    //0费用的课程、余额抵扣实际支付费用，直接支付成功
    if (response?.data?.status == 1) {
      clearInterval(timer.current);
      // 追加课支付
      if (isDlc) {
        message.success('支付成功');
      } else {
        handleShowResult(response?.data);
      }
      return;
    }

    /**
     * 不然就是返回二维码，然后去轮询
     * 轮询的参数是response?.data?.check属性后面？的截取部分
     */
    const check = response?.data?.check || '';
    const arr = check.split('?');
    const paramsString = arr[arr.length - 1];

    // 显示二维码弹窗
    PayCodeRef.current = PayCode.showPayCode({
      type: payType,
      data: {
        money: payMoney,
        qrCode: response?.data?.qr,
      },
      onClose: () => {
        clearInterval(timer.current);
      },
      onSuccess: async () => {
        checkPayStatus({ paramsString, balance, payType, fqiNum, manual: true, isDlc });
      },
    });

    // 开始轮询支付状态
    timer.current = setInterval(
      () => checkPayStatus({ paramsString, balance, payType, fqiNum, isDlc }),
      3000,
    );
  };

  // 套餐购买
  const packagesBuy = async (item: { sid: any; mentor: any }) => {
    // 获取套餐详情
    const detail = await getPackagesDetail(item);
    if (!detail.success) return;
    const data = detail?.data?.salesmix_class || [];

    // 显示确定订单弹窗
    OrderPayModal.showOrderPay({
      type: 'package',
      payPrice: detail?.data?.topay,
      originalPrice: detail?.data?.salesmix?.maxprice,
      balance: detail?.data?.paycredit,
      coupon: detail?.data?.paycredit || 0,
      data,
      // 点击支付
      onPay: (data) => handlePay({ ...data, sid: item.sid, mentor: item.mentor }),
      fqOptions: detail?.data?.fqipay_fqs || [],
    });
  };

  // 课程购买
  const courseBuy = async (item: { classid: any; mentor: any }) => {
    // 获取课程详情
    const detail = await getCourseDetail(item);
    if (!detail.success) return;
    classDetailRef.current = detail?.data?.course;

    // 单个课程是用 price + topay
    // 和套餐购买保持统一去手动去替换对应的key
    const course = detail?.data?.course || {};
    course.oldprice = course.price;
    course.price = detail?.data?.topay;

    const data = [course];

    // 显示确定订单弹窗
    OrderPayModal.showOrderPay({
      type: 'course',
      payPrice: detail?.data?.topay,
      originalPrice: detail?.data?.course?.oldprice,
      balance: detail?.data?.paycredit,
      coupon: detail?.data?.paycredit || 0,
      // oldStudentCoupon: 150,
      data,
      coupons: detail?.data?.coupons,
      // 点击支付
      onPay: (data) => handlePay({ ...data, classid: item.classid, mentor: item.mentor }),
      secskill: detail?.data?.secskill,
      fqOptions: detail?.data?.fqipay_fqs || [],
    });
  };

  // 课程DLC购买
  const courseDLCBuy = async (item: { lid: any }) => {
    // 获取DLC详情
    const detail = await getCourseDLCDetail(item);
    if (!detail.success) return;

    const course = {
      oldprice: detail?.topay,
      price: detail?.topay,
      thumb: detail?.course?.thumb,
      name: detail?.data?.name,
    };

    const data = [course];

    // 显示确定订单弹窗
    OrderPayModal.showOrderPay({
      type: 'dlc',
      payPrice: detail?.topay,
      originalPrice: detail?.topay,
      balance: detail?.paycredit,
      data,
      payType: [1, 2],
      // 点击支付
      onPay: (data) => handlePay({ ...data, lid: item.lid, isDlc: true }),
    });
  };
  return { packagesBuy, courseBuy, courseDLCBuy };
};
export default useBuy;
